package org.wiztools.thegreatwall;

import java.io.IOException;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.wiztools.commons.Implementation;

/**
 *
 * @author subhash
 */
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        final String usernameEmail = req.getParameter("username");
        final String password = req.getParameter("password");

        Operations ops = Implementation.of(Operations.class);
        try{
            LoginStatus loginStatus = ops.login(usernameEmail, password);
            switch(loginStatus){
                case SUCCESS:
                    HttpSession session = req.getSession(true);
                    session.setAttribute("username", usernameEmail);
                    resp.sendRedirect(req.getContextPath());
                    break;
                case INVALID_PASSWORD:
                    req.setAttribute("username", usernameEmail);
                    req.setAttribute("errors", Arrays.asList(new String[]{"Invalid password."}));
                    req.getRequestDispatcher("/loginForm.jsp").include(req, resp);
                    break;
                case INVALID_USERNAME:
                    req.setAttribute("username", usernameEmail);
                    req.setAttribute("errors", Arrays.asList(new String[]{"Invalid username/email."}));
                    req.getRequestDispatcher("/loginForm.jsp").include(req, resp);
                    break;
            }
        }
        catch(OperationException ex){
            throw new IOException(ex);
        }
    }
    
}
